package com.example.gcmpractice;

import com.example.utils.Constants;
import com.google.android.gcm.GCMRegistrar;


import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainAct extends Activity {
	
	/**
	 * The application's context.
	 */
	private Context appContext;
	
	/**
	 * The registration button on the interface.
	 */
	private Button gcmRegButton;
	/**
	 * Onclick listener for registering for push notification service.
	 */
	private RegClick regClick;
	/**
	 * Onclick listener for unregistering from push notification service.
	 */
	private UnRegClick unRegClick;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_act);
        
        //This hack is necessary to fix a bug associated with connection libraries in Android
        //Do not remove.
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
		     System.setProperty("http.keepAlive", "false");
		}
		
		appContext = this.getApplicationContext();
		gcmRegButton = (Button) findViewById(R.id.gcm_regButton);
		regClick = new RegClick();
		unRegClick = new UnRegClick();
        
		gcmRegButton.setOnClickListener(new RegClick());
		gcmRegButton.setText("Register");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_act, menu);
        return true;
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	GCMRegistrar.onDestroy(appContext);
    }
    
    private class RegClick implements View.OnClickListener {

		public void onClick(View v) {
	    	//The device needs to be able to support GCM. Otherwise an exception will be thrown.
	    	GCMRegistrar.checkDevice(appContext);
	    	//Remove after development is complete. Used to check whether Manifest is setup properly.
	    	GCMRegistrar.checkManifest(appContext);
	    	//Check if this device is registered with the cloud.
	    	String GCMregID = GCMRegistrar.getRegistrationId(appContext);
	    	if (GCMregID.equals("")) {
	    		//The device is not registered with the cloud. Register using the API Project ID.
	    		GCMRegistrar.register(appContext, Constants.API_PROJECT_ID);
	    	}
	    	gcmRegButton.setOnClickListener(unRegClick);
	    	gcmRegButton.setText("Unregister");
	    	//Otherwise, this device has already registered with Google Cloud Messaging.	
		}
    }
    private class UnRegClick implements View.OnClickListener {
		public void onClick(View v) {
			GCMRegistrar.unregister(appContext);
    		gcmRegButton.setOnClickListener(regClick);
    		gcmRegButton.setText("Register");
		}
    }
}
